import { Service } from 'egg';
import { School } from '../model/School';
import { College } from '../model/College';

class SchoolService extends Service {
    /**
     * 查询学校列表
     */
    public async searchSchoolList() {
        const resultSchool = await this.ctx.model.School.findAll<School>({
            attributes: ['school_id', 'school_name', 'school_badge', 'school_status'],
            where: { is_delete: '1' }
        });
        if (resultSchool.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return resultSchool;
    }

    /**
     * 创建学校
     * @param school_name 
     * @param school_badge 
     * @param college 
     */
    public async createSchool(school_name: string, school_badge: string, college: any) {
        let schoolData: any = {};
        schoolData.school_id = this.ctx.helper.genUUID();
        schoolData.school_name = school_name;
        schoolData.school_badge = school_badge;
        schoolData.school_status = '1';
        schoolData.is_delete = '1';
        const tran = await this.ctx.model.transaction();
        try {
            const resultSchool = await this.ctx.model.School.create(schoolData, { transaction: tran });
            console.log(resultSchool);
            if (college && college.length > 0) {
                for (let i = 0; i < college.length; i++) {
                    college[i]['college_id'] = this.ctx.helper.genUUID();
                    college[i]['school_id'] = schoolData.school_id;
                    college[i]['college_status'] = '1';
                    college[i]['is_delete'] = '1';
                }
                const resultCollege = await this.ctx.model.College.bulkCreate(college, { transaction: tran });
                console.log(resultCollege);
            }
            tran.commit();
        } catch (e) {
            await tran.rollback();
            this.ctx.logger.error(e);
            throw new Error(JSON.stringify({ code: 2, msg: '创建失败' }));
        }
    }

    /**
     * 启用、停用学校
     * @param school_id 
     * @param type 
     */
    public async startAndStopSchool(school_id: string, type: string) {
        const resultSchool = await this.ctx.model.School.update({ school_status: type }, { where: { school_id } });
        if (resultSchool[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
        }
    }

    /**
     * 根据id查找学校
     * @param school_id 
     */
    public async searchSchoolById(school_id: string) {
        const resultSchool: any = await this.ctx.model.School.findOne<School>({
            attributes: ['school_id', 'school_name', 'school_badge'],
            where: { school_id }
        });
        if (!resultSchool) {
            throw new Error(JSON.stringify({ code: 2, msg: '查找失败' }));
        }
        const resultCollege = await this.ctx.model.College.findAll<College>({ attributes: ['college_id', 'college_name'], where: { school_id, is_delete: '1' } });
        let resultData: any = {};
        resultData.school_id = resultSchool.school_id;
        resultData.school_name = resultSchool.school_name;
        resultData.school_badge = resultSchool.school_badge;
        if (resultCollege.length > 0) {
            resultData.college = resultCollege;
        }
        return resultData;
    }

    /**
     * 保存修改学校
     * @param school_name 
     * @param school_badge 
     */
    public async updateSchool(school_id: string, school_name: string, school_badge) {
        const resultSchool = await this.ctx.model.School.update({ school_name, school_badge }, { where: { school_id } });
        if (resultSchool[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
        }
    }

    /**
     * 添加学院
     * @param college_name 
     * @param school_id 
     */
    public async createCollege(college_name: string, school_id: string, age_limit: number) {
        const resultSchool: any = await this.ctx.model.School.findOne<School>({ attributes: ['school_id'], where: { school_id } });
        if (!resultSchool) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有找到对应的学校' }));
        }
        let submitData: any = {};
        submitData.college_id = this.ctx.helper.genUUID();
        submitData.school_id = school_id;
        submitData.college_name = college_name;
        submitData.age_limit = age_limit;
        submitData.college_status = '1';
        submitData.is_delete = '1';
        const resultCollege = await this.ctx.model.College.create(submitData);
        if (!resultCollege) {
            throw new Error(JSON.stringify({ code: 2, msg: '添加失败' }));
        }
    }

    /**
     * 启用、停用学院
     * @param param 
     */
    public async startAndStopCollege(param: any) {
        const resultCollege = await this.ctx.model.College.update({ college_status: param.type }, { where: { college_id: param.college_id } });
        if (resultCollege[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
        }
    }

    /**
     * 修改学院
     * @param param 
     */
    public async updateCollege(param: any) {
        const resultCollege = await this.ctx.model.College.update({ college_name: param.college_name, age_limit: param.age_limit }, { where: { college_id: param.college_id } });
        if (resultCollege[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '更新失败' }));
        }
    }

    /**
     * 根据学校id查找学院列表
     * @param param 
     */
    public async searchCollegeBySchoolId(param: any) {
        const result = await this.ctx.model.College.findAll<College>({ attributes: ['college_id', 'college_name', 'age_limit', 'college_status'], where: { school_id: param.school_id } });
        if (result.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return result;
    }

    /**
     * 根据学院名字查找学院
     * @param param 
     */
    public async searchCollegeByName(param: any) {
        let queryStr: string = '';
        if (param.college_name) {
            queryStr = `SELECT c.college_id,c.college_name,c.age_limit FROM t_college c INNER JOIN t_school s ON c.school_id=s.school_id WHERE c.college_name LIKE '%${param.college_name}%' AND c.college_status='1' AND s.school_status='1'`;
        }
        if (param.school_id) {
            queryStr = `SELECT c.college_id,c.college_name,c.age_limit FROM t_college c INNER JOIN t_school s ON c.school_id=s.school_id WHERE c.school_id='${param.school_id}' AND c.college_status='1' AND s.school_status='1'`;
        }
        if (param.school_id && param.college_name) {
            queryStr = `SELECT c.college_id,c.college_name,c.age_limit FROM t_college c INNER JOIN t_school s ON c.school_id=s.school_id WHERE c.college_name LIKE '%${param.college_name}%' AND c.school_id='${param.school_id}' AND c.college_status='1' AND s.school_status='1'`;
        }
        if (!param.school_id && !param.college_name) {
            queryStr = `SELECT c.college_id,c.college_name,c.age_limit FROM t_college c INNER JOIN t_school s ON c.school_id=s.school_id WHERE c.college_status='1' AND s.school_status='1'`;
        }
        const resultCollege = await this.ctx.model.query(queryStr, {
            type: this.ctx.model.QueryTypes.SELECT
        })
        if (resultCollege.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return resultCollege;
    }

}
export default SchoolService;